//
//  PhotoListViewController.m
//  TestDemo
//
//  Created by apple on 16/5/2.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PhotoListViewController.h"
#import "PhotoViewCell.h"
#import "PhotoModel.h"
#import "mm_picRecodeDataModel.h"

#define photoCellID @"photoCellID"
#define navBarHeight 90

@interface PhotoListViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,PhotoViewCellDelegate>

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *photoList;
@property(nonatomic,weak)UIButton *deleteBtn;

/** 用于显示大图 */
@property(nonatomic,strong)UIImageView *bigImageView;

/** 存放被删除的图片索引 */
@property(nonatomic,strong)NSMutableArray *deletedIndexes;

@end

@implementation PhotoListViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor= [UIColor whiteColor];
    //创建导航条
    [self setupNavigationBar];
    
    //创建图片列表视图
    [self setupCollectionView];
    
}

-(void)setupNavigationBar{
    
    UIView *navBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, navBarHeight)];
//    navBar.backgroundColor = [UIColor blueColor];
    [self.view addSubview:navBar];
    
    //返回按钮
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, 30, 42, 40)];
    [backBtn setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [navBar addSubview:backBtn];
    
    //标题
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(backBtn.frame)+30, 30, 200, 40)];
    title.text = @"图片预览";
    title.textColor = [UIColor darkGrayColor];
    title.font = [UIFont systemFontOfSize:30];
    [navBar addSubview:title];
    
    //编辑、删除按钮
    CGFloat btnW = 73;
    CGFloat btnH = 44;
    CGFloat marginRight = 50;
    CGFloat marginTop = 25;
    CGFloat btnX = self.view.frame.size.width - marginRight - btnW;
    UIButton *editBtn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, marginTop, btnW, btnH)];
    [editBtn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitle:@"取消" forState:UIControlStateSelected];
    [editBtn addTarget:self action:@selector(editBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [navBar addSubview:editBtn];
    if (!self.editOperation) {
        editBtn.hidden = YES;
    }
    
    btnX = btnX - marginRight - btnW;
    
    UIButton *deletBtn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, marginTop, btnW, btnH)];
    [deletBtn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
    [deletBtn setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateDisabled];
    [deletBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deletBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [deletBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    deletBtn.enabled = false;
    [deletBtn addTarget:self action:@selector(deleteBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [navBar addSubview:deletBtn];
    self.deleteBtn = deletBtn;
    if (!self.editOperation) {
        deletBtn.hidden = YES;
    }
    
    CGFloat spH = 11;
    CGFloat spY = navBarHeight - spH;
    UIImageView *splitView = [[UIImageView alloc]initWithFrame:CGRectMake(0, spY, self.view.frame.size.width, spH)];
    splitView.image = [UIImage imageNamed:@"渐变分割线.png"];
}

-(void)setupCollectionView{
    //确定是水平滚动，还是垂直滚动
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    flowLayout.itemSize = CGSizeMake(220, 165);
    CGFloat margin = 30;
    // 3.设置cell之间的水平间距
    flowLayout.minimumInteritemSpacing = margin;
    // 4.设置cell之间的垂直间距
    flowLayout.minimumLineSpacing = margin;
    // 5.设置四周的内边距
    flowLayout.sectionInset = UIEdgeInsetsMake(flowLayout.minimumLineSpacing, margin, 0, margin);
    
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height - navBarHeight;
    self.collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, navBarHeight, width, height) collectionViewLayout:flowLayout];
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    // 注册cell(告诉collectionView将来创建怎样的cell)
    UINib *nib = [UINib nibWithNibName:@"PhotoViewCell" bundle:nil];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:photoCellID];
}

-(NSMutableArray *)photoList{
    if (_photoList == nil) {
        mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
        _photoList = picDataModel.arrForAllCapturePic;
    }
    return _photoList;
}

-(void)backBtnClicked{
    //跳回上一级页面
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 点击图片放大方法

-(UIImageView *)bigImageView{
    if (_bigImageView == nil) {
        _bigImageView  = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _bigImageView.hidden = YES;
        _bigImageView.backgroundColor = [UIColor blackColor];
        _bigImageView.contentMode = UIViewContentModeScaleToFill;
        [_bigImageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissBigImage)]];
        _bigImageView.userInteractionEnabled = YES;
        [self.view addSubview:_bigImageView];
    }
    return _bigImageView;
}

-(void)dismissBigImage{
    self.bigImageView.hidden = YES;
}

#pragma mark - collectionView数据源方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.photoList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.获得cell
    PhotoViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:photoCellID forIndexPath:indexPath];
    // 2.传递模型
    cell.photo = self.photoList[indexPath.item];
    cell.indexPath = indexPath;
    cell.delegate = self;
    [cell unCheckForCheckbxo];//reloadData 后需要重新设置复选框的选中状态
    return cell;
}

#pragma mark - collectionView代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //点击图片放大
    PhotoModel *photo = self.photoList[indexPath.item];
    self.bigImageView.image = photo.image;
    self.bigImageView.hidden = NO;
}

#pragma mark - photoViewCell代理方法

-(void)checkboxBtn:(UIButton *)btn clickedAtIndexPath:(NSIndexPath *)indexPath{
    if (btn.selected) {//选中
        [self.deletedIndexes addObject:indexPath];
    }else{//取消选中
        //从数组中移除
        for (NSIndexPath *index in self.deletedIndexes) {
            if (index == indexPath) {
                [self.deletedIndexes removeObject:indexPath];
            }
        }
    }
}

#pragma mark - 编辑按钮
-(void)editBtnClicked:(UIButton *)btn{
    btn.selected = !btn.selected;
    NSString *noticName = nil;
    if (btn.selected) {//编辑
        noticName = beginEditNoticeName;
        self.deleteBtn.enabled = YES;
    }else{//取消
        noticName = cancelEditNoticeName;
        self.deleteBtn.enabled = NO;
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:noticName object:nil];
}

#pragma mark - 删除按钮
-(void)deleteBtnClicked{
    if (self.deletedIndexes.count==0) {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"请勾选要删除的图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }
    
    mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
    NSMutableArray *deleteObjecs = [NSMutableArray array];
    for (NSIndexPath *indexPath in self.deletedIndexes) {
        
        PhotoModel *pm = self.photoList[indexPath.item];
        if (pm.newImage) {//如果是新加的图片
            //新图片直接删除
            [picDataModel.arrForNewImage removeObject:pm];
        }else{//数据库中的图片
            //保存删除的图片
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:pm.fileId forKey:deletedImageName];
            [dic setObject:pm.itemId forKey:@"ITEM_ID"];
            [dic setObject:@"D" forKey:@"STATUS"];
            [picDataModel.arrForDeletedImages addObject:dic];
        }
        [deleteObjecs addObject:pm];
    }//end for
    [self.photoList removeObjectsInArray:deleteObjecs];
    [self.collectionView reloadData];
    self.deletedIndexes = nil;//每删除一次重新清空数组
}

-(NSMutableArray *)deletedIndexes{
    if (_deletedIndexes == nil) {
        _deletedIndexes = [NSMutableArray array];
    }
    return _deletedIndexes;
}
@end
